/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.group4.controller;

import com.group4.entity.Parent;
import com.group4.entity.Parent_;
import com.group4.entity.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Victor Cernea
 */
@Stateless
public class ParentFacade extends AbstractFacade<Parent> {
    @PersistenceContext(unitName = "HighSchoolPortal_pu")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public ParentFacade() {
        super(Parent.class);
    }
    public Parent findByLogin(String username, String password) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Parent> cq = builder.createQuery(Parent.class);
        
        Root<Parent> query = cq.from(Parent.class);
        Join<Parent,User> parentUser = query.join(Parent_.user);
        
        Path<String> uname = parentUser.get("login");
        Path<String> p = parentUser.get("password");
                
        Predicate userCond = builder.equal(uname, username);
        Predicate passCond = builder.equal(p, password);
        cq.where(builder.and(userCond, passCond));
        TypedQuery<Parent> a = em.createQuery(cq);
        List<Parent> parentList = a.getResultList();
        if(parentList.size() > 0)
            return parentList.get(0);
        else
            return null;
    }
    
}
